(function() {
	//https://www.googleapis.com/language/translate/v2?key=AIzaSyDtJJ1QEf55Q6dT4d5tsyvMAAv0GfheGAc&q=flowers&source=en&target=fr&callback=handleResponse&prettyprint=true
	var api = "https://www.googleapis.com/language/translate/v2?key=AIzaSyDtJJ1QEf55Q6dT4d5tsyvMAAv0GfheGAc&q=${word}&%{source}&%{target}&callback=${guid}";
	
	function format(template, json){
        if (!json) 
            return template;
        return template &&
        template.replace(/(\$|%)\{(.+?)\}/g, function(all, flag, key) {
            return (flag == "%" ? key + "=" : "") + json[key];
        })
    }
	function translation(node) {
		var params = {
			guid: "translation_" + (+new Date).toString(36),
			word: node.nodeType == 3 ? node.nodeValue : node.value,
			source: "zh-CN",
			target: "en"
		};
		if (!params.word) return;
		if (!(/[\u4e00-\u9fa5]/.test(params.word))) {
			params.target = "zh-CN";
			/* TODO : 处理其他语言 */
			params.source = "en";	
		}
		
		window[params.guid] = function(result) {
			var data = result.data;
			if (!data || !data.translations) return;
			var results = [];
			for (var i = 0; i < data.translations.length; i++) {
				var translation = data.translations[i];
				results.push(translation.translatedText);
			}
			if (node.nodeType == 3) 
				node.nodeValue = results.join("\n");
			else 
				node.value = results.join("\n");
		};
		
		var e = document.createElement('script');
		e.setAttribute('src', format(api, params));
		document.body.appendChild(e);
	}
	
	function scanNode(node) { // 翻译文本
		if (!node) return;
		if (node.nodeType == 3) {
			translation(node);			
			return;
		}
        var nodes = node.childNodes, i = nodes.length;
        while (i--) {
            scanNode(nodes[i]);
        }
	}
	 
    function scaner(document) {
		var node = document.activeElement;
        if (/^i?frame$/i.test(node.tagName)) { // 嵌套扫描 code
            try {
                scaner(node.contentWindow.document);
            } 
            catch (e) {
            }
			return
        }
		if (document.designMode == "on") { // 编辑模式
			scanNode(node);
			return;
		}
        if (/^(textarea|input)$/i.test(node.tagName)) { // 输入框，采用编码 code
        	translation(node);
            return;
        }
		if (/^(div)$/i.test(node.tagName)) { // 可编辑的div
			scanNode(node);
			return;
		}
    }
    if (/^(community|bbs)\.csdn\.net$/.test(document.domain)) { // 处理导航页面 code
        document.domain = "csdn.net";
    }
    scaner(document);
})();
